<?php
$code = <<<EOF
package dao

import (
    redisUtils "git.inke.cn/bpc/framework/server/utils/redis"
	"{$data['root_path_name']}/{$data['service_name']}/model"
	"context"
	"encoding/json"
	"fmt"
	"git.inke.cn/BackendPlatform/golang/logging"
	"git.inke.cn/BackendPlatform/golang/redis"
	"time"
)
const (
    {$data['model_name']}ItemCacheKey = "{$data['service_name_key']}:{$data['model_name']}:item:%d"//todo 类型：【】，用途【】
)
//================================公共通用方法===============================
func (d *Dao) HasCache{$data['model_name']}(ctx context.Context, cacheKey string) bool {
	keyExists, _ := d.{$data['redis_client_name']}.Exists(ctx, cacheKey)
	return keyExists
}

/**
 * @Description: 查询当前key是否还有过期时间
 * @param ctx
 * @param key
 * @return int：-1表示不过期，-2表示key不存在
 * @return error
 */
func (d *Dao) Ttl{$data['model_name']}(ctx context.Context, key string) (int, error) {
	logger := logging.For(ctx, "func", "Ttl{$data['model_name']}", "key", key)
	t, err := redis.Int(d.{$data['redis_client_name']}.Do(ctx, "ttl", key))
	if err != nil {
		logger.Errorf("[redis.Int] error,value:%v, err:%+v", t, err)
	}
	return t, err
}

//是否需要加过期时间：如果key存在并且没有设置过期时间，则加上过期时间。
func (d *Dao) IsAddExpire{$data['model_name']}(ctx context.Context, key string, time time.Duration) error {
	t, _ := d.Ttl{$data['model_name']}(ctx, key)
	if t == -1 {
		return d.Expire{$data['model_name']}(ctx, key, time)
	}
	return nil
}


/**
* 删除缓存
 */
func (d *Dao) DelKey{$data['model_name']}(ctx context.Context, key string) error {
	var (
		logger = logging.For(ctx, "dao", "delKey", "key", key)
		err    error
	)

	_, err = d.{$data['redis_client_name']}.Del(ctx, key)
	if err != nil {
		logger.Errorf("Del error: %v", err)
		return err
	}

	logger.Debugf("success")
	return nil
}

/**
 * @Description: 通过ID生成cacheKey
 * @param UID
 * @return string
 */
func Get{$data['model_name']}ItemCacheKey(id int64) string {
	return fmt.Sprintf({$data['model_name']}ItemCacheKey, id)
}

//设置过期时间
func (d *Dao) Expire{$data['model_name']}(ctx context.Context, key string, time time.Duration) error {
	err := d.{$data['redis_client_name']}.Expire(ctx, key, time)
	if err != nil {
		logging.Errorf("[Expire] error, err:%+v", err)
	}
	return err
}

//===================================string===================================
/**
 * @Description：添加一条数据（string），设置过期时间
 * @param ctx
 * @param uid
 * @param data
 * @return err
 */
func (d *Dao) Add{$data['model_name']}CacheExpired(ctx context.Context, data interface{}, cacheKey string, expireTime int) (err error) {
	logger := logging.For(ctx, "func", "Add{$data['model_name']}CacheExpired", "data", data)
	//插入数据
	jsonData, err := json.Marshal(data)
	if err != nil {
		logger.Errorf("json.Marshal error, data: %v, err: %v", data, err)
		return
	}

	_, err = d.{$data['redis_client_name']}.SetExSecond(ctx, cacheKey, jsonData, expireTime)
	if err != nil {
		logger.Errorf("[redis.SetExSecond] error,data:%v, err:%+v", data, err)
		return
	}
	return nil
}

/**
 * @Description：添加一条数据（string），不设置过期时间
 * @param ctx
 * @param uid
 * @param data
 * @return err
 */
func (d *Dao) Add{$data['model_name']}Cache(ctx context.Context, data interface{}, cacheKey string) (err error) {
	logger := logging.For(ctx, "func", "Add{$data['model_name']}Cache", "data", data)
	//插入数据
	jsonData, err := json.Marshal(data)
	if err != nil {
		logger.Errorf("json.Marshal error, data: %v, err: %v", data, err)
		return
	}

	_, err = d.{$data['redis_client_name']}.Set(ctx, cacheKey, jsonData)
	if err != nil {
		logger.Errorf("[redis.SetExSecond] error,data:%v, err:%+v", data, err)
		return
	}
	return nil
}


/**
 * @Description: 获取缓存（string）
 * @param ctx
 * @param cacheKey
 * @param record：需要传一个引用类型
 * @return err：只有正确拿到数据才会返回nil，其他情况都会返回错误
 */
func (d *Dao) Get{$data['model_name']}(ctx context.Context, cacheKey string,record interface{}) (err error) {
	logger := logging.For(ctx, "func", "Get{$data['model_name']}", "cacheKey", cacheKey)
	data, err := d.{$data['redis_client_name']}.Get(ctx, cacheKey)
	if len(data) > 0 {
		err = json.Unmarshal(data, record)
		if err != nil {
			logger.Errorf("json Unmarshal data:%s err:%s", data, err)
		}
		return
	}

	return
}

/** 
 * @Description: incrBy
 * @param ctx
 * @param key
 * @param value
 * @return err
 */
func (d *Dao) {$data['model_name']}IncrBy(ctx context.Context, key string, value int) (err error) {
	logger := logging.For(ctx, "func", "{$data['model_name']}IncrBy", "key", key, "value", value)
	res, err := d.{$data['redis_client_name']}.Incrby(ctx, key, value)
	if err != nil {
		logger.Errorf("{$data['model_name']}Incr,res:%v, err: %v", res, err)
		return
	}
	logger.Debugf("{$data['model_name']}Incr,res:%v, err: %v", res, err)
	return
}

//===================================hash===================================

/**
 * @Description: 存储用户操作记录的值（hash）
 * @param ctx
 * @param key
 * @param fieldK
 * @param fieldV
 * @return ret：true || false
 * @return err
 */
func (d *Dao) HSet{$data['model_name']}(ctx context.Context, key string, fieldK, fieldV string) (err error) {
	logger := logging.For(ctx, "func", "HSet{$data['model_name']}", "key", key, "fieldK", fieldK, "fieldV", fieldV)
	res, err := d.{$data['redis_client_name']}.HSet(ctx, key, fieldK, fieldV)
	if err != nil || res != 1 {
		logger.Errorf("[HSet] error,res:%v, err:%+v", res, err)
	}
	return
}


/**
 * @Description: 存储值（hash）
 * @param ctx
 * @param key
 * @param mapString
 * @return ret：true || false
 * @return err
 */
func (d *Dao) HMSet{$data['model_name']}(ctx context.Context, key string, mapString map[string]string) (err error) {
	logger := logging.For(ctx, "func", "HMSet{$data['model_name']}", "key", key, "mapString", mapString)
	if len(mapString) <= 0 || mapString == nil {
		return fmt.Errorf("mapString is nil")
	}
	fields := make([]interface{}, 0)
	for i, v := range mapString {
		fields = append(fields, i, v)
	}
	res, err := d.{$data['redis_client_name']}.HMSet(ctx, key, fields...)
	if err != nil || res != "OK" {
		logger.Errorf("[HMSet] error,res:%v, err:%+v", res, err)
	}
	return
}

/**
 * @Description：获取hash结构中某一个字段（hash）
 * @param ctx
 * @param key
 * @param field:需要获取的字段
 * @return res：仅为字段的值
 * @return err
 */
func (d *Dao) HGet{$data['model_name']}(ctx context.Context, key string, field string) (res string, err error) {
	logger := logging.For(ctx, "func", "HGet{$data['model_name']}", "key", key, "field", field)

	res, err = d.{$data['redis_client_name']}.HGet(ctx, key, field)
	if err != nil {
		logger.Errorf("[HGet] error,res:%v, err:%+v", res, err)
		return
	}
	return
}

/**
 * @Description：获取hash结构中某一些字段（hash）
 * @param ctx
 * @param key
 * @param fields:需要获取的字段
 * @return res：仅为字段的值
 * @return err
 */
func (d *Dao) HMGet{$data['model_name']}(ctx context.Context, key string, fields []interface{}) (res []string, err error) {
	logger := logging.For(ctx, "func", "HMGet{$data['model_name']}", "key", key, "fields", fields)

	res, err = d.{$data['redis_client_name']}.HMGet(ctx, key, fields...)
	if err != nil {
		logger.Errorf("[HMGet] error,res:%v, err:%+v", res, err)
		return
	}
	return
}

/**
 * @Description：获取hash结构的全量值（hash）
 * @param ctx
 * @param key
 * @return mapString
 * @return err
 */
func (d *Dao) HGetAll{$data['model_name']}(ctx context.Context, key string) (mapString map[string]string, err error) {
	logger := logging.For(ctx, "func", "HGetAll{$data['model_name']}", "key", key)
	mapString, err = d.{$data['redis_client_name']}.HGetAll(ctx, key)
	if err != nil {
		logger.Errorf("[HGetAll] error,mapString:%v, err:%+v", mapString, err)
		return
	}
	return
}

/**
 * @Description：删除hash中的某个值（hash）
 * @param ctx
 * @param key
 * @param field:需要删除的字段
 * @return res：成功的结果数量
 * @return err
 */
func (d *Dao) HDel{$data['model_name']}(ctx context.Context, key string, field string) (res int, err error) {
	logger := logging.For(ctx, "func", "HDel{$data['model_name']}", "key", key, "field", field)

	res, err = d.{$data['redis_client_name']}.HDel(ctx, key, field)
	if err != nil {
		logger.Errorf("[HDel{$data['model_name']}] error,res:%v, err:%+v", res, err)
		return
	}
	return
}


//===================================set===================================
//无序集合中添加值（set）
func (d *Dao) SAdd{$data['model_name']}(ctx context.Context,key string, value ...interface{}) error {
	logger := logging.For(ctx, "func", "SAdd{$data['model_name']}Info", "value", value)
	res, err := d.{$data['redis_client_name']}.SAdd(ctx, key, value...)
	if err != nil {
		logger.Errorf("[SAdd] error,value:%v, err:%+v", res, err)
	}
	logger.Infof("SAdd{$data['model_name']}  result : %v", res)
	return err
}

//无序集合查询是否有值（set）
func (d *Dao) SIsMember{$data['model_name']}(ctx context.Context, key string , value string) (bool, error) {
	logger := logging.For(ctx, "func", "SIsMember{$data['model_name']}", "key", key, "value", value)
	res, err := d.{$data['redis_client_name']}.SIsMember(ctx, key, value)
	if err != nil {
		logger.Errorf("[SIsMember] error,res:%v, err:%+v", res, err)
		return false, err
	}
	logger.Infof("SIsMember{$data['model_name']}  result : %v", res)
	return res, err
}

//获取set集合的全量值
func (d *Dao) Smembers{$data['model_name']}(ctx context.Context, key string) (res []string,err error) {
	logger := logging.For(ctx, "func", "Smembers{$data['model_name']}", "key", key)
	res, err = d.redis.SMembers(ctx, key)
	if err != nil{
	    logger.Errorf("Smembers{$data['model_name']}  res:%v, err:%+v", res, err)
	}
	return
}

//无序集合删除某个值（set）
func (d *Dao) SRem{$data['model_name']}(ctx context.Context, key string ,value ...interface{}) (int, error) {
	logger := logging.For(ctx, "func", "SRem{$data['model_name']}", "key", key, "value", value)
	res, err := d.{$data['redis_client_name']}.SRem(ctx, key, value...)
	if err != nil {
		logger.Errorf("[SRem] error,res:%v, err:%+v", res, err)
		return 0, err
	}
	logger.Infof("SRem{$data['model_name']}  result : %v", res)
	return res, err
}

//无序集合随机获取N个值（set）
func (d *Dao) SRandMember{$data['model_name']}(ctx context.Context, key string, count int) ([]string, error) {
	logger := logging.For(ctx, "func", "SRem{$data['model_name']}", "key", key, "count", count)
	iRes, err := d.{$data['redis_client_name']}.Do(ctx, "SRANDMEMBER", key, count)
	res, err := redis.Strings(iRes, err)
	if err != nil {
		logger.Errorf("[SRANDMEMBER] error,res:%v, err:%+v", res, err)
		return make([]string, 0), err
	}
	logger.Debugf("SRandMember{$data['model_name']}  result : %v", res)
	return res, err
}

//无序集合包含多少个值（set）
func (d *Dao) SCard{$data['model_name']}(ctx context.Context, key string) (int, error) {
	logger := logging.For(ctx, "func", "SCard{$data['model_name']}", "key", key)
	res, err := d.{$data['redis_client_name']}.Do(ctx, "SCARD", key)
	count, err := redis.Int(res, err)
	if err != nil {
		logger.Errorf("[SCARD] error,res:%v, err:%+v", res, err)
		return 0, err
	}

	logger.Infof("SCard{$data['model_name']}  result : %v", res)
	return count, err
}

//===================================zset===================================
/** 
 * @Description: 分页信息（zset）
 * @param ctx
 * @param offset：当前查询的页是从哪个下标开始查起
 * @param totalCount：总共有多少条数据
 * @param defaultOffset：每页多少条数据
 * @return res
 * @return pagination
 */
func (d *Dao) Get{$data['model_name']}ForPagination(ctx context.Context, offset, defaultOffset int, cacheKey string) (res []model.{$data["model_name"]}Model, pagination redisUtils.PaginatorMap) {
    logger := logging.For(ctx, "func", "Get{$data['model_name']}ForPagination", "cacheKey", cacheKey)
	//初始化数据格式，防止返回null这样的数据
	res = make([]model.{$data["model_name"]}Model, 0)

	//计算分页信息
	totalCount, err := d.{$data['redis_client_name']}.ZCard(ctx, cacheKey)
	if err != nil {
		logger.Errorf("get totalCount error, cacheKey: %v, err: %v", cacheKey, err)
		return
	}

	pagination = redisUtils.PaginatorForRedis(offset, totalCount, defaultOffset)

	//拿出当前页数据
	resDb, err := d.{$data['redis_client_name']}.Zrevrange(ctx, cacheKey, pagination.StartIndex, pagination.EndIndex)

	if err != nil {
		logger.Errorf("get data from redis error or no data ,cacheKey:%v,resDb:%v,error:%v", cacheKey, resDb, err)
		return
	}

	if len(resDb) <= 0 {
		return
	}

	//json转结构体，结构体合并为数组
	for _, val := range resDb {
		var item model.{$data["model_name"]}Model
		str := []byte(val)
		err := json.Unmarshal(str, &item)
		if err != nil {
			logger.Errorf("json.Unmarshal err,json: %v, err: %v", val, err)
			continue
		}
		res = append(res, item)
	}

	return
}

/**
 * @Description: 批量插入zset列表
 * @param ctx
 * @param uid
 * @param data
 * @return err
 */
func (d *Dao) BatchAdd{$data['model_name']}ForList(ctx context.Context, records []model.{$data['model_name']}Model, cacheKey string) (err error) {
	logger := logging.For(ctx, "func", "BatchAdd{$data['model_name']}ForList")
	//制作数据
	data := make([]interface{}, 0)
	for _, v := range records {
		jsonData, err := json.Marshal(v)
		if err != nil {
			logger.Errorf("json.Marshal error, record: %v, err: %v", records, err)
			continue
		}
		data = append(data, v.Score)
		data = append(data, jsonData)
	}

	_, err = d.{$data['redis_client_name']}.ZAdd(ctx, cacheKey, data...)
	if err != nil {
		logger.Errorf("[redis.ZAdd] error,record:%v, err:%+v", records, err)
		return
	}
	return nil
}

/**
 * @Description: zset添加一条数据
 * @param ctx
 * @param uid
 * @param data
 * @return err
 */
func (d *Dao) ZAddOne{$data['model_name']}(ctx context.Context, record interface{}, score int64, cacheKey string) (err error) {
	logger := logging.For(ctx, "func", "ZAddOne{$data['model_name']}", "record", record)
	//插入数据
	jsonData, err := json.Marshal(record)
	if err != nil {
		logger.Errorf("json.Marshal error, record: %v, err: %v", record, err)
		return err
	}
	_, err = d.{$data['redis_client_name']}.ZAdd(ctx, cacheKey, score, jsonData)
	if err != nil {
		logger.Errorf("[redis.ZAdd] error,record:%v, err:%+v", record, err)
		return
	}
	return nil
}

/**
 * @Description: 计算ZSet的元素数量
 * @param ctx
 * @param cacheKey
 * @return ret
 * @return err
 */
func (d *Dao) ZCard{$data['model_name']}ForZset(ctx context.Context, cacheKey string) (ret int, err error) {
	logger := logging.For(ctx, "func", "ZCard{$data['model_name']}ForList", "cacheKey", cacheKey)
	ret, err = d.{$data['redis_client_name']}.ZCard(ctx, cacheKey)
	if err != nil {
		logger.Errorf("[redis.ZCard] error,ret:%v, err:%+v", ret, err)
	}
	return
}


/**
 * @Description: 删除zset集合中的数据
 * @param ctx
 * @param cacheKey
 * @param start：从什么index开始，包括这个start
 * @param stop：从什么index结束，包括这个stop
 * @return ret：成功删除的数据数量
 * @return err
 */
func (d *Dao) ZRemRangeByRank{$data['model_name']}ForZSet(ctx context.Context, cacheKey string, start, stop int) (ret int, err error) {
	logger := logging.For(ctx, "func", "ZRemRangeByRank{$data['model_name']}ForZSet", "cacheKey", cacheKey)
	ret, err = d.{$data['redis_client_name']}.ZRemrangebyrank(ctx, cacheKey, start, stop)
	if err != nil {
		logger.Errorf("[redis.ZREMRANGEBYSCORE] error,ret:%v, err:%+v", ret, err)
	}
	return
}

/**
 * @Description: 通过分数范围删除zset集合中的数据【ZREMRANGEBYSCORE salary 4000 6000  #移除4000<=salary<=6000】
 * @param ctx
 * @param cacheKey
 * @param start：从什么什么分数开始，包括这个start
 * @param stop：从什么index结束，包括这个stop
 * @return ret：成功删除的数据数量
 * @return err
 */
func (d *Dao) ZRemRangeByScore{$data['model_name']}ForZSet(ctx context.Context, cacheKey string, start, stop int64) (ret int64, err error) {
	logger := logging.For(ctx, "func", "ZRemRangeByScore{$data['model_name']}ForZSet", "cacheKey", cacheKey)
	retInterface, err := d.{$data['redis_client_name']}.Do(ctx, "ZREMRANGEBYSCORE", cacheKey, start, stop)
	ret = retInterface.(int64)
	if err != nil {
		logger.Errorf("[redis.ZRemrangebyrank] error,ret:%v, err:%+v", ret, err)
	}
	return
}

EOF;
?>
<?= $code?>
